<?php namespace Common\Model;
use Hdphp\Model\Model;
class Goods extends Model{
	protected $table = 'goods';
	protected $validate = array(
		array('gname','required','商品名称不能为空',3,3),
	);
	protected $auto = array(
		array('gtime','time','function',3,1),
		array('type_tid','getType','method',3,3)
	);
	
	//商品添加
	public function store(){
		
		if(!$this->create()) return false;
		//添加商品第一张表，返回自增id
//		p(Q('post.'));
		$gid = $this->add();
		
		$details=new \Common\Model\Details;
		$details->create();
		$details->data['goods_gid']=$gid;
		
		$details->add();
		//添加商品属性表
		$goodsAttrModel = new \Common\Model\GoodsAttr;
		//属性添加
		foreach (Q('post.attr') as $taid => $v) {
			if($v){
				$data = array(
					'gtvalue'=>$v,
					'typeattr_taid'=>$taid,
					'goods_gid'=>$gid
				);
				$goodsAttrModel->add($data);
			}
		}
		//规格添加
		$spec = Q('post.spec');
		if($spec){
			$value = $spec['value'];
			foreach ($value as $taid => $v) {
				foreach ($v as $kk => $vv) {
					$data = array(
						'gtvalue'=>$vv,
						'typeattr_taid'=>$taid,
						'goods_gid'=>$gid,
						'added'=>$spec['added'][$taid][$kk]
					);
					$goodsAttrModel->add($data);
				}
			}
		}
//		exit;
		return true;
	}
	
	//修改
	public function edit(){
//		p(Q('POST.'));exit;
		if(!$this->create()) return false;
		$gid=Q('post.gid',0,'intval');
//		$pic=$this->where("gid={$gid}")->pluck('pic');
//		unlink($pic);
		$this->save();
		$detModel=new \Common\Model\Details;
		$detModel->create();
		$detModel->where("goods_gid={$gid}")->save();
		
		$goodsAttrModel = new \Common\Model\GoodsAttr;
		$goodsAttrModel->where("goods_gid={$gid}")->delete();
		//属性添加
		foreach (Q('post.attr') as $taid => $v) {
			if($v){
				$data = array(
					'gtvalue'=>$v,
					'typeattr_taid'=>$taid,
					'goods_gid'=>$gid
				);
				$goodsAttrModel->add($data);
			}
		}
		//规格添加
		$spec = Q('post.spec');
		if($spec){
			$value = $spec['value'];
			foreach ($value as $taid => $v) {
				foreach ($v as $kk => $vv) {
					$data = array(
						'gtvalue'=>$vv,
						'typeattr_taid'=>$taid,
						'goods_gid'=>$gid,
						'added'=>$spec['added'][$taid][$kk]
					);
					$goodsAttrModel->add($data);
				}
			}
		}
		return true;
	}
	
	public function getType(){
		$cid = Q('post.category_cid',0,'intval');
		$type = new \Common\Model\CateGory;
		return $type->where("cid={$cid}")->pluck('type_tid');
	}
}
